import * as React from 'react';
import * as TinyMCE from 'react-tinymce';
import { RouteComponentProps } from 'react-router';
import { observer } from 'mobx-react';
import { Form, Input, DatePicker, Button, Table, Col, Select, message } from 'antd';

import { ImageUploader } from '../../../../components/ImageUploader';
import { SearchInput } from '../../../../components/SearchInput';
import { TopicModel } from '../../../../../model/assets/standard/TopicModel';
import {CREATE_SUCCESS_REDIRECT_DELAY} from "../../../../../service/Config";

const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
const tailFormItemLayout = {
    wrapperCol: {
        span: 14,
        offset: 6,
    },
};

interface TopicEditorState {
    store?: TopicModel;
    coverImageFileList?: any[];
    slidesFileList?: any[];
    isEditMode?: boolean;
}

@observer
export class TopicEditor extends React.Component<RouteComponentProps<any, any>, TopicEditorState> {

    constructor(props) {
        super(props);
        this.initState();
    }

    initState() {
        let store: TopicModel;
        let isEditMode = this.props.route.path !== 'topic/create';

        if (!isEditMode) { // 创建
            store = new TopicModel();
        }
        else { // 编辑
            store = new TopicModel(this.props.params.id);
            store.fetchData().catch(res => {
                message.error(`数据请求失败`, 2.5);
            });
        }

        this.state = {
            store,
            coverImageFileList: null,
            slidesFileList: null,
            isEditMode: isEditMode
        };
    }

    private onSubmit = () => {
        this.state.store.save().then(
            res => message.success(res.message, CREATE_SUCCESS_REDIRECT_DELAY, () => {
                if (!this.state.isEditMode) {
                    location.href = '#/content/assets/topic/manager'
                }
            }),
            err => message.error(err.message, 2.5)
        );
    }

    private renderCoverImageUploader() {
        var {store, coverImageFileList} = this.state;
        var onChange = (fileList) => this.setState({ coverImageFileList: fileList });
        var onUpdate = (fileList) => store.data.coverImageUrl = fileList.length ? fileList[0].url : "";

        if (!coverImageFileList && store.data.coverImageUrl) {
            coverImageFileList = [{
                uid: -1,
                url: store.data.coverImageUrl
            }];
        }

        return <ImageUploader fileList={coverImageFileList} onChange={onChange} onUpdate={onUpdate} />;
    }

    private renderEvents() {
        var {store} = this.state;

        return store.data.events.map((item, index) => {
            return <Input.Group size="large" key={index}>
                <Col span={8}>
                    <SearchInput
                        value={item.name}
                        onChange={(name: string) => { store.fetchEventOptions(name) }}
                        placeholder="请输入专题名称查询并选择"
                        options={store.eventOptions}
                        onSelect={(selectedId: string) => store.updateEventOptions(index, selectedId)} />
                </Col>
                <Col span={4}>
                    <Button shape="circle" icon="plus" onClick={() => store.addEventAt(index + 1)} />
                    {store.data.events.length > 1 && <Button shape="circle" icon="delete" onClick={() => store.deleteEventAt(index)} />}
                </Col>
            </Input.Group>;
        });
    }

    render() {
        var {store, isEditMode} = this.state;

        return <Form horizontal>
            <FormItem
                {...formItemLayout}
                label="名称"
                required
                validateStatus={store.nameValid ? 'success' : 'error'}
            >
                <Input placeholder="请输入专活动名称" value={store.data.name} onChange={e => store.data.name = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="标题"
            >
                <Input placeholder="请输入专活动标题" value={store.data.title} onChange={e => store.data.title = e.target['value']} />
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="专题封面图"
                extra="图片建议尺寸：750像素*387像素，长方形"
                required
            >
                {this.renderCoverImageUploader()}
            </FormItem>
            <FormItem
                {...formItemLayout}
                label="专题简介"
                required
            >
                {(!isEditMode || store.data.desc) && <TinyMCE
                    content={store.data.desc}
                    config={{
                        plugins: 'link code',
                        toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code',
                        language: 'zh_CN',
                    }}
                    onChange={(e) => store.data.desc = e.target.getContent()}
                />}
            </FormItem>
            <Form.Item label="专题内容" labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} extra="最少添加4个活动">
                {this.renderEvents()}
            </Form.Item>
            <FormItem {...tailFormItemLayout}>
                <Button type="primary" size="large" onClick={this.onSubmit} loading={store.isSubmiting} style={{ marginRight: 10 }}>保存</Button>
                <Button size="large" onClick={() => location.href = '#/content/assets/topic/manager'}>返回列表</Button>
            </FormItem>
        </Form>;
    }
}